package juc.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQueueTest {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<DelayObject> blockingQueue = new DelayQueue<>();
        blockingQueue.put(new DelayObject("A",1000*10));
        blockingQueue.put(new DelayObject("B",4000*10));
        blockingQueue.put(new DelayObject("C",3000*10));
        blockingQueue.put(new DelayObject("D",2000*10));

        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
    }

}

class DelayObject implements Delayed{

    private String name;

    private long time;

    public DelayObject(String name, Integer delayTime) {
        this.name = name;
        this.time = System.currentTimeMillis()+delayTime;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        long diff =time-System.currentTimeMillis();
        return unit.convert(diff,TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed obj) {
        if (this.time<((DelayObject)obj).time)
            return -1;
        if (this.time>((DelayObject)obj).time)
            return 1;
        return 0;
    }

    @Override
    public String toString() {
        return "DelayObject{" +
                "name='" + name + '\'' +
                ", time=" + time +
                '}';
    }
}
